﻿//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

using P2.Cuberry.Framework.BOLBase;
using P2.Cuberry.Framework.Helper;
using P2.Cuberry.Framework.Helper.Configuration;
using P2.Cuberry.Framework.Security;
using P2.Cuberry.Modules.Framework.ModuleManager.DAL;


namespace P2.Cuberry.Modules.Framework.ModuleManager.BusinessEntities
{
    public class XConfigWorkflowUIControls : BizObject, INotifyPropertyChanged
    {

        #region Constructors

        public XConfigWorkflowUIControls()
        {
            Modified = false;
        }

        public XConfigWorkflowUIControls(DAL.XConfigWorkflowUIControls configUIControls)
        {
            Load(configUIControls);
            Modified = false;
        }

        #endregion


        #region Members

        int _workFlowStatusId = 0;
        public int WorkFlowStatusId
        {
            get { return _workFlowStatusId; }
            set
            {
                if (value != _workFlowStatusId)
                {
                    _workFlowStatusId = value;
                    Modified = true;
                } 
            }
        }

        string _statusName = string.Empty;
        public String StatusName
        {
            get { return _statusName; }
            set 
            {
                if (value != _statusName)
                    _statusName = value;
            }
        }

        string _moduleName = String.Empty;
        public string ModuleName
        {
            get { return _moduleName; }
            set
            {
                if (value != _moduleName)
                {
                    _moduleName = value;
                    Modified = true;
                }
            }
        }

        string _dialogName = String.Empty;
        public string DialogName
        {
            get { return _dialogName; }
            set
            {
                if (value != _dialogName)
                {
                    _dialogName = value;
                    Modified = true;
                }
            }
        }

        string _controlName = String.Empty;
        public string ControlName
        {
            get { return _controlName; }
            set
            {
                if (value != _controlName)
                {
                    _controlName = value;
                    Modified = true;
                }
            }
        }

        string _controlType = String.Empty;
        public string ControlType
        {
            get { return _controlType; }
            set
            {
                if (value != _controlType)
                {
                    _controlType = value;
                    Modified = true;
                }
            }
        }

        bool? _isActive = false;
        public bool? IsActive
        {
            get { return _isActive; }
            set
            {
                if (value != _isActive)
                {
                    _isActive = value;
                    Modified = true;
                }
            } 
        }

        public Module ParentModule { set; get; }

        #endregion


        #region Read Operations

        public void Load(DAL.XConfigWorkflowUIControls sourceEntity)
        {
            try
            {
                if (sourceEntity != null)
                {
                    this.WorkFlowStatusId = sourceEntity.StatusID;
                    this.ModuleName = sourceEntity.ModuleName;                    
                    this.DialogName = sourceEntity.DialogName;
                    this.ControlName = sourceEntity.ControlName;
                    this.ControlType = sourceEntity.ControlType;
                    this.IsActive = sourceEntity.IsActive;
                    this.StatusName = this.GetMyStatus(this.WorkFlowStatusId);
                                       

                    //Default Fields                
                    this.CreatedBy = sourceEntity.CreatedBy;
                    this.CreatedOn = sourceEntity.CreatedOn;
                    this.EditedBy = sourceEntity.EditedBy;
                    this.EditedOn = sourceEntity.EditedOn;
                    this.Timestamp = sourceEntity.TStamp;
                    //this.StatusID = sourceEntity.StatusID.GetValueOrDefault(P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName).StatusID);

                }
                else
                {
                    this.WorkFlowStatusId = 0;
                    this.ModuleName = string.Empty;
                    this.DialogName = string.Empty;
                    this.ControlName = string.Empty;
                    this.ControlType = string.Empty;
                    this.IsActive = false;

                    //Default Fields
                    this.CreatedBy = String.Empty;
                    this.EditedBy = String.Empty;
                    P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus initStatus = P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName);
                    this.StatusID = initStatus.StatusID;
                }
                Modified = false;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }

        private string GetMyStatus(int statusId)
        {
            if (statusId == -1)
            {
                return "New";
            }

            var currentStatus = string.Empty;

            string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
            using (ModuleManagerDataContext db = new ModuleManagerDataContext(connectionString))
            {
                var result = (from statuses in db.EnterpriseWorkflowStatus
                                        where statuses.StatusID == statusId
                                        select statuses).First();

                switch (P2Translator.CultureLanguageFU)
                {
                    case "En":
                        {
                            currentStatus = result.StatusNameEn;
                            break;
                        }
                    case "Ar":
                        {
                            currentStatus = result.StatusNameAr;
                            break;
                        }
                    case "De":
                        {
                            currentStatus = result.StatusNameDe;
                            break;
                        }
                    default:
                        {
                            currentStatus = result.StatusNameEn;
                            break;
                        }
                }
            }
            return currentStatus;
        }

        public static ObservableCollection<XConfigWorkflowUIControls> GetXConfigWorkFlowUIControls(Module xMod, PropertyChangedEventHandler onChange)
        {
            try
            {
                ObservableCollection<XConfigWorkflowUIControls> itemsCollection = new ObservableCollection<XConfigWorkflowUIControls>();

                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (ModuleManagerDataContext db = new ModuleManagerDataContext(connectionString))
                {
                    var xConfigUIControls = from tranItem in db.XConfigWorkflowUIControls                                            
                                        where tranItem.ModuleName == xMod.ModuleName
                                        select tranItem;
                    if (xConfigUIControls.Count() > 0)
                    {
                        foreach (var xConfigUIControl in xConfigUIControls)
                        {
                            itemsCollection.Add(new XConfigWorkflowUIControls(xConfigUIControl) { ParentModule = xMod });
                        }
                    }
                }

                return itemsCollection;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", "XAppResources", System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }

        public static IList<BusinessEntities.XDialogName> GetDialogNames(Module module)
        {
            try
            {
                IList<BusinessEntities.XDialogName> dialogList = new List<BusinessEntities.XDialogName>();
                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (ModuleManagerDataContext db = new ModuleManagerDataContext(connectionString))
                {
                    var configUIControls = (from tran in db.XConfigWorkflowUIControls
                                            where tran.ModuleName == module.ModuleName
                                            orderby tran.DialogName ascending
                                            select tran.DialogName).Distinct();

                    if (configUIControls.Count() > 0)
                    {
                        foreach (var dialog in configUIControls)
                        {
                            dialogList.Add(new XDialogName { DialogName = dialog });
                        }
                    }            
                }
                return dialogList;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", "XAppResources", System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }

        public static IList<BusinessEntities.EnterpriseWorkflowStatus> GetEnterpriseWorkFlowStatuses(string moduleName)
        {
            try
            {
                IList<BusinessEntities.EnterpriseWorkflowStatus> statusList = new List<BusinessEntities.EnterpriseWorkflowStatus>();
                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (ModuleManagerDataContext db = new ModuleManagerDataContext(connectionString))
                {
                    var statuses = (from tran in db.EnterpriseWorkflowStatus
                                            join ewo in db.EnterpriseWorkflowObject on tran.WorkflowID equals ewo.WorkflowID
                                            where ewo.ModuleName == moduleName
                                            orderby tran.StatusName ascending
                                            select tran).Distinct();

                    if (statuses.Count() > 0)
                    {
                        foreach (var status in statuses)
                        {
                            var entWorkflowStatus = new EnterpriseWorkflowStatus();
                            entWorkflowStatus.EnterpriseWorkflowStatusId = status.StatusID;

                            switch (P2Translator.CultureLanguageFU)
                            {
                                case "En":
                                    {
                                        entWorkflowStatus.WorkflowStatus = status.StatusNameEn;
                                        break;
                                    }
                                case "Ar":
                                    {
                                        entWorkflowStatus.WorkflowStatus = status.StatusNameAr;
                                        break;
                                    }
                                case "De":
                                    {
                                        entWorkflowStatus.WorkflowStatus = status.StatusNameDe;
                                        break;
                                    }
                                default:
                                    {
                                        entWorkflowStatus.WorkflowStatus = status.StatusNameEn;
                                        break;
                                    }
                            }

                            statusList.Add(entWorkflowStatus);
                        }
                    }
                }
                return statusList;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", "XAppResources", System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }

        }

        public static void FillConfigWorkFlowUIControlsForSelectedDialog(Module xMod, XDialogName dialogName)
        {
            try
            {
                xMod.ConfigWorkFlowUIControls.Clear();

                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (ModuleManagerDataContext db = new ModuleManagerDataContext(connectionString))
                {
                    var configUIControls = from tranItem in db.XConfigWorkflowUIControls
                                        where tranItem.DialogName == dialogName.DialogName && tranItem.ModuleName == xMod.ModuleName
                                        select tranItem;
                    if (configUIControls.Count() > 0)
                    {
                        foreach (var uiControls in configUIControls)
                        {
                            xMod.ConfigWorkFlowUIControls.Add(new XConfigWorkflowUIControls(uiControls) { ParentModule = xMod });
                        }
                    }
                }
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", "XAppResources", System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }

        #endregion

        #region Update Operations

        public P2MessageStack InsertAndUpdate(ModuleManagerDataContext db)
        {
            P2MessageStack MessageStack = new P2MessageStack();

            try
            {
                if (string.IsNullOrEmpty(this.CreatedBy)) 
                    this.CreatedBy = User.Current.UserID;
                
                this.EditedBy = User.Current.UserID;
                DAL.XConfigWorkflowUIControls editedItem;
                
                if (this.CreatedOn == null)
                {
                    editedItem = new DAL.XConfigWorkflowUIControls()
                    {
                        StatusID = this.WorkFlowStatusId,
                        ModuleName = this.ModuleName,
                        DialogName = this.DialogName,
                        ControlName = this.ControlName,
                        ControlType = this.ControlType,
                        IsActive = this.IsActive,

                        CreatedBy = this.CreatedBy,
                        CreatedOn = DateTime.Now,
                        EditedBy = this.EditedBy,
                        EditedOn = DateTime.Now
                    };
                    db.AddToXConfigWorkflowUIControls(editedItem);
                }
                else
                {
                    editedItem = (from ti in db.XConfigWorkflowUIControls
                                  where ti.StatusID == this.WorkFlowStatusId && ti.ModuleName == this.ModuleName && ti.DialogName == this.DialogName && ti.ControlName == this.ControlName
                                  select ti).First();

                    if (editedItem.TStamp == this.Timestamp)
                    {
                        editedItem.StatusID = this.WorkFlowStatusId;
                        editedItem.ModuleName = this.ModuleName;
                        editedItem.DialogName = this.DialogName;
                        editedItem.ControlName = this.ControlName;
                        editedItem.ControlType = this.ControlType;
                        editedItem.IsActive = this.IsActive;

                        editedItem.EditedBy = this.EditedBy;
                        editedItem.EditedOn = DateTime.Now;
                    }
                    else
                    {
                        MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("TMsg_PaymentNotUpdated")));
                    }
                }
            }
            catch (Exception ex) //AM:TC!!
            {
                MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("Error_Error")));
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
            return MessageStack;
        }

        public void Delete(ModuleManagerDataContext db)
        {
            if (this.WorkFlowStatusId !=0 && this.ModuleName != String.Empty && this.DialogName != string.Empty && this.ControlName != string.Empty)
            {
                var item = (from ti in db.XConfigWorkflowUIControls
                            where this.WorkFlowStatusId == ti.StatusID && this.ModuleName == ti.ModuleName && this.DialogName == ti.DialogName && this.ControlName == ti.ControlName
                            select ti).First();
                db.DeleteObject(item);
                db.SaveChanges();
            }
        }

        #endregion

        #region Validation
        //Empty
        #endregion

        #region "Copy operations"

        public XConfigWorkflowUIControls GetCopy()
        {
            try
            {
                XConfigWorkflowUIControls newItem = new XConfigWorkflowUIControls();
                newItem.ParentModule = this.ParentModule;
                newItem.ModuleName = this.ModuleName;

                newItem.WorkFlowStatusId = this.WorkFlowStatusId;
                newItem.DialogName = this.DialogName;
                newItem.ControlName = this.ControlName;
                newItem.ControlType = this.ControlType;
                newItem.IsActive = this.IsActive;

                newItem.Timestamp = this.Timestamp;
                newItem.Modified = this.Modified;
                return newItem;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }

        public void UpdateFrom(XConfigWorkflowUIControls sourceItem)
        {
            try
            {
                this.ParentModule = sourceItem.ParentModule;
                this.ModuleName = sourceItem.ModuleName;

                this.WorkFlowStatusId = sourceItem.WorkFlowStatusId;
                this.DialogName = sourceItem.DialogName;
                this.ControlName = sourceItem.ControlName;
                this.ControlType = sourceItem.ControlType;
                this.IsActive = sourceItem.IsActive;

                this.Timestamp = sourceItem.Timestamp;
                this.Modified = sourceItem.Modified;
            }
            catch (System.Exception ex)
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }

        #endregion

        #region Property Changed

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler Handler = PropertyChanged;
            if (Handler != null) 
                Handler(this, new PropertyChangedEventArgs(propertyName));
        }

        public void OnAllPropertiesChanged()
        {
            OnPropertyChanged("WorkFlowStatusId");
            OnPropertyChanged("ModuleName");
            OnPropertyChanged("DialogName");
            OnPropertyChanged("ControlName");
            OnPropertyChanged("ControlType");
            OnPropertyChanged("IsActive");
        }

        #endregion


        #region Validator

        public override P2Validator Validator
        {
            get
            {
                if (_validator == null)
                {
                    _validator = new P2Validator(Properties.Settings.Default.ModuleName, this.EntityName, "DialogName", this);
                }
                return _validator;
            }
        }

        #endregion
    }
}
